


//
//  ZLoginViewController.m
//  ZQLearn
//
//  Created by 朵 on 2019/4/22.
//  Copyright © 2019年 macfeel. All rights reserved.
#import "WXApi.h"
#import "AppDelegate.h"
#import "ZLoginViewController.h"
#import "ZAgreementViewController.h"
#import "ZRootViewController.h"
#import "ToolClass.h"
@interface ZLoginViewController ()

@property (weak, nonatomic) IBOutlet UIButton *wxLoginBtn;

@property (weak, nonatomic) IBOutlet UIButton *gouxuanBtn;

@property (weak, nonatomic) IBOutlet UITextField *telTextFd;
@property (weak, nonatomic) IBOutlet UITextField *msgCodeTextFd;

@property (weak, nonatomic) IBOutlet UIButton *loginBtn;


@property (weak, nonatomic) IBOutlet UIButton *msgCodeBtn;

@property (nonatomic,assign)BOOL isSelected;

@end

@implementation ZLoginViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = kWhiteColor;
    self.navigationItem.leftBarButtonItem = nil;
    [self.navigationItem setItemWithTitle:@"登录" textColor:kDarkGrayColor fontSize:18 itemType:center];
    
    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(35, CGRectGetMaxY(self.telTextFd.frame)-5, ScreenWidth-70, 0.5)];
    line1.backgroundColor = kLightGrayColor;
    [self.view addSubview:line1];
    
    UIView *line2 = [[UIView alloc]initWithFrame:CGRectMake(35, CGRectGetMaxY(self.msgCodeTextFd.frame)-5, ScreenWidth-70, 0.5)];
    line2.backgroundColor = kLightGrayColor;
    [self.view addSubview:line2];
    self.msgCodeBtn.backgroundColor = NColorFrom16RGB(0x1fd989);
    self.msgCodeBtn.layer.cornerRadius = 5.f;
    self.msgCodeBtn.layer.masksToBounds = YES;
    self.loginBtn.backgroundColor = NColorFrom16RGB(0x1fd989);
    self.loginBtn.layer.cornerRadius = 5.f;
    self.loginBtn.layer.masksToBounds = YES;
    self.isSelected = NO;
    
    ////微信登录按钮隐藏
    if ([WXApi isWXAppInstalled]) {
        self.wxLoginBtn.hidden = false;
    }else{
        self.wxLoginBtn.hidden = YES;
    }
    self.wxLoginBtn.backgroundColor = kWhiteColor;
    [self.wxLoginBtn setTitleColor:NColorFrom16RGB(0x1fd989) forState:UIControlStateNormal];
    self.wxLoginBtn.layer.cornerRadius = 5.f;
    self.wxLoginBtn.layer.masksToBounds = YES;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getUserInfo:) name:kWXLoginNoti object:nil];
    // Do any additional setup after loading the view from its nib.
}


///获取微信登录信息后调用自己服务器的接口
-(void)getUserInfo:(NSNotification *)noti{
    
    ///这个标记了请求时的传参方式
    [UserModel shareInstance].isLogin = YES;
    NSDictionary *para = noti.object;
    YYLog(@"%@",para);
    NSDictionary *dict = @{@"openId":para[@"openid"],@"photo":para[@"headimgurl"],@"nickName":para[@"nickname"],@"deviceToken":kDeviceToken,};
    WeakStament(ws);
    
    [ZNetworkService postRequestWithBaseUrl:kwxLoginUrl setParameters:dict success:^(id result) {
        YYLog(@"%@",result);
        if ([result[@"errorCode"]integerValue]==0) {
            NSDictionary *dict = result[@"result"];
            [UserInfoSave shareInstance].photo = dict[@"photo"];
            [UserInfoSave shareInstance].nickName = dict[@"nickName"];
            [UserInfoSave shareInstance].openid = dict[@"openid"];
            [UserInfoSave shareInstance].ID = dict[@"id"];
            YYLog(@"用户id:%@",[UserInfoSave shareInstance].ID);
            [[NSUserDefaults standardUserDefaults]setObject:dict[@"id"] forKey:kUserId];
            [[NSUserDefaults standardUserDefaults]synchronize];
            [ws closeView];
            [UserModel shareInstance].isLogin = NO;
        }
    } fail:^(NSError *error) {
        
    } delegater:nil];
    
}
    


- (IBAction)gouXuanAction:(UIButton *)sender {
    
    ///按钮勾选状态
    sender.selected = !sender.selected;
    if (sender.selected) {
        [sender setImage:[UIImage imageNamed:@"xuasnzhong"] forState:UIControlStateSelected];
        self.isSelected = YES;
//        self.pwdTF.secureTextEntry = NO;
        
    }else{
        [sender setImage:[UIImage imageNamed:@"yuan"] forState:UIControlStateNormal];
        self.isSelected = NO;
//        self.pwdTF.secureTextEntry = YES;
    }
}



- (IBAction)msgCodeAction:(UIButton *)sender {
    
    if (self.telTextFd.text.length<11) {
        [AFToast showText:@"请输入正确电话号码"];
        return;
    }
    
    
    if (![ToolClass validateMobile:self.telTextFd.text]) {
        [AFToast showText:@"请输入正确电话号码"];
        return;
    }
    [self msgcode];
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [self.msgCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
//                [self.msgCodeBtn setTitleColor:[UIColor colorFromHexCode:@"FB8557"] forState:UIControlStateNormal];
                self.msgCodeBtn.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self.msgCodeBtn setTitle:[NSString stringWithFormat:@"%.2d秒", seconds] forState:UIControlStateNormal];
//                [self.msgCodeBtn setTitleColor:[UIColor colorFromHexCode:@"979797"] forState:UIControlStateNormal];
                self.msgCodeBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

///获取验证码
- (void)msgcode{

    NSDictionary *dic =  @{@"phone":self.telTextFd.text?:@"",};
    [ZNetworkService getRequestWithBaseUrl:kMsgCodeUrl setParameters:dic success:^(id result) {
        
        YYLog(@"%@",result);
        if ([result[@"errorCode"]integerValue]==0) {
            [AFToast showText:@"验证码发送成功"];
        }
        
    } fail:^(NSError *error) {
        
    } delegater:nil];
    
}


- (IBAction)userAgreementAction:(id)sender {
                ZAgreementViewController *ag = [ZAgreementViewController new];
                [self.navigationController pushViewController:ag animated:YES];
}

#pragma mark - 登录
- (IBAction)loginActoin:(UIButton *)sender {
    
    if (self.telTextFd.text.length<11) {
        [AFToast showText:@"请输入正确的手机号"];
        return;
    }
    if (self.msgCodeTextFd.text.length<3) {
        [AFToast showText:@"请检查验证码"];
        return;
    }
    if (self.isSelected==NO) {
        [AFToast showText:@"请先阅读并同意用户协议"];
        return;
    }
    [UserModel shareInstance].isLogin = YES;
    ///18700866341 测试帐号
    
    NSDictionary *dic =  @{@"phone":self.telTextFd.text?:@"",@"codeRandom":self.msgCodeTextFd.text?:@"",@"deviceToken":kDeviceToken,@"deviceType":@"2",};
    [ZNetworkService postRequestWithBaseUrl:kLoginUrl setParameters:dic success:^(id result) {
        YYLog(@"%@",result);
        if ([result[@"errorCode"]integerValue]==0) {
            NSDictionary *userDict = result[@"result"];
            [UserInfoSave shareInstance].ID = userDict[@"id"];
            YYLog(@"用户id:%@",[UserInfoSave shareInstance].ID);
            [[NSUserDefaults standardUserDefaults]setObject:userDict[@"id"] forKey:kUserId];
            
            [UserInfoSave shareInstance].nickName = userDict[@"nickName"];
            [[NSUserDefaults standardUserDefaults]setObject:userDict[@"nickName"] forKey:@"nickName"];
            [UserInfoSave shareInstance].phone = userDict[@"phone"];
            [[NSUserDefaults standardUserDefaults]setObject:userDict[@"phone"] forKey:@"phone"];
            [UserInfoSave shareInstance].vipLevel = userDict[@"vipLevel"];
             [[NSUserDefaults standardUserDefaults]setObject:userDict[@"vipLevel"] forKey:@"vipLevel"];
            [UserInfoSave shareInstance].birthday = userDict[@"birthday"];
            [UserInfoSave shareInstance].gender = userDict[@"sex"];
            [UserInfoSave shareInstance].refereeNumber = userDict[@"refereeNumber"];
             [UserInfoSave shareInstance].vipLevel = userDict[@"vipLevel"];
            
            //地址需要进行拼接
            [UserInfoSave shareInstance].area = [NSString stringWithFormat:@"%@%@%@",userDict[@"province"],userDict[@"city"],userDict[@"area"]];
            [UserInfoSave shareInstance].address =userDict[@"address"];
            [UserInfoSave shareInstance].school = userDict[@"school"];
            
            [UserInfoSave shareInstance].grade = userDict[@"grade"];
            
            [UserInfoSave shareInstance].hobby = userDict[@"hobby"];
            
            ///后台数据中 integral  这个是个int 但是从字典取出来后确被强制转换了类型，是id类型，所以需要最后赋值时候将这个类型明确下来不然赋值会报错的
            [UserInfoSave shareInstance].integral = userDict[@"integral"];
           
            [self saveInfoWithDict:userDict];
            
//            YYLog(@"%@",userDict[@"nickName"]);
//            YYLog(@"%@",userDict[@"phone"]);
            ////
            [self closeView];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [AFToast showText:@"登录成功"];
            });
            [UserModel shareInstance].isLogin = NO;
//            UserInfoSave *user = [UserInfoSave mj_objectWithKeyValues:result[@"result"]];
//            [self.userDataArray addObject:user];
            ///
//            [UserInfoSave shareInstance]
        }else{
            [AFToast showText:@"验证码错误"];
        }
    } fail:^(NSError *error) {
        YYLog(@"%@",error);
    } delegater:nil];
}

#pragma mark - 个人信息保存到沙盒
///个人信息保存到沙盒
- (void)saveInfoWithDict:(NSDictionary *)dic{
    [[NSUserDefaults standardUserDefaults]setObject:[UserInfoSave shareInstance].birthday forKey:@"birthday"];
     [[NSUserDefaults standardUserDefaults]setObject:[UserInfoSave shareInstance].gender forKey:@"gender"];
    [[NSUserDefaults standardUserDefaults]setObject:[UserInfoSave shareInstance].vipLevel forKey:@"vipLevel"];
    ///邀请码
    [[NSUserDefaults standardUserDefaults]setObject:[UserInfoSave shareInstance].refereeNumber forKey:@"inviteCode"];
    ////area 包括省市区
     [[NSUserDefaults standardUserDefaults]setObject:[UserInfoSave shareInstance].area forKey:@"area"];
     [[NSUserDefaults standardUserDefaults]setObject:[UserInfoSave shareInstance].address forKey:@"address"];
     [[NSUserDefaults standardUserDefaults]setObject:[UserInfoSave shareInstance].school forKey:@"school"];
    
    [[NSUserDefaults standardUserDefaults]setObject:[UserInfoSave shareInstance].grade forKey:@"grade"];
    [[NSUserDefaults standardUserDefaults]setObject:[UserInfoSave shareInstance].hobby forKey:@"hobby"];
    [[NSUserDefaults standardUserDefaults]setObject:[UserInfoSave shareInstance].integral forKey:@"integral"];
    ///同步这个很重要，可以保证信息及时存储
    [[NSUserDefaults standardUserDefaults]synchronize];
}

-(void)closeView{
    
    //因为这些控制器没有交给导航来管理所以点击没有反应
    //    TabBarViewController *tab = [[TabBarViewController alloc]init];
    [UIView animateWithDuration:.3 animations:^{
        self.view.alpha = 0;
    } completion:^(BOOL finished) {
        
        //        AppDelegate *app = [UIApplication sharedApplication].delegate;
        ZRootViewController *tab = [[ZRootViewController alloc]init];
        AppDelegate *appDelegate = (id)([UIApplication sharedApplication].delegate);
        appDelegate.window.rootViewController = tab;
        //        [appDelegate initRootViewCtrlByTabBar];
        
    }];
}


#pragma mark - 微信登录

- (IBAction)wxLoginAction:(UIButton *)sender {
    
    if([WXApi isWXAppInstalled]){//判断用户是否已安装微信App
        
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.state = @"wx_oauth_authorization_state";//用于保持请求和回调的状态，授权请求或原样带回
        req.scope = @"snsapi_userinfo";//授权作用域：获取用户个人信息
        
        [WXApi sendReq:req];//发起微信授权请求
    }else{
        
        //提示：未安装微信应用或版本过低
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}


@end
